package tmt.usercenter.web.domain.converter;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by ThreeManTeam on 2017/5/10.
 */

@Converter
public class StringAndListConverter implements AttributeConverter<List<String>, String> {

	@Override
	public String convertToDatabaseColumn(List<String> attribute) {
		if (attribute == null)
			return "";
		StringBuffer result = new StringBuffer();
		attribute.forEach(x -> result.append("|").append(x));
		return result.toString().replaceFirst("\\|", "");
	}

	@Override
	public List<String> convertToEntityAttribute(String dbData) {
		if (dbData == null || "".equals(dbData.trim()))
			return new ArrayList<>();

		return Arrays.stream(dbData.split("\\|")).filter(x -> x.length() > 0).collect(Collectors.toList());
	}
}
